<template>
	<div :class="className" style="width: 100%">
		<el-table-draggable
			:column="useColumnDrag"
			:handle="handler"
			@sort="handleDragSort"
			@input="handleDragInput"
		>
			<el-table
				ref="table"
				v-loading="loading"
				:data="datas"
				:data-size="datas.length"
				:default-sort="defaultSort"
				:header-cell-style="getRowClass"
				:show-summary="ownSummary.show"
				:summary-method="getSummaries"
				border
				row-key="id"
				class="realize-table-body"
				element-loading-spinner="el-icon-loading"
				style="width: 100%"
				@sort-change="changeTableSort"
			>
				<el-table-column
					v-if="xvhao"
					align="center"
					:label="$t('common.serial_number')"
					type="index"
					width="50"
					fixed="left"
					prop="index"
				>
					<template slot-scope="scope">
						{{ getSerialNum(scope.$index) }}
					</template>
				</el-table-column>
				<!-- 手动计算列宽常規字段列 -->
				<template v-for="(item, index) in curFieldList">
					<!-- 序号 -->
					<AFTableColumn
						v-if="item.show"
						:key="index"
						:autoColor="item.autoColor"
						:fit="item.fit"
						:fixed="item.fixed"
						:header="item.header"
						:isBtn="item.isBtn"
						:label="item.label"
						:property="item.prop"
						:showCopy="item.showCopy"
						:sortable="item.orderColumn ? 'custom' : null"
						:styleCellColor="item.styleCellColor"
						:tipsText="item.tipsText"
						:tooltipHeader="item.tooltipHeader"
						:width="item.width"
						:min-width="item.minWidth"
						:show-overflow-tooltip="
							item.showOverflowTooltip || false
						"
						align="center"
					>
						<template v-slot="scope">
							<template v-if="item.buttonLists">
								<template
									v-for="(item1, index1) in item.buttonLists"
								>
									<el-button
										v-if="item1.filtersShow(scope.row)"
										:key="index1 + 'id'"
										:disabled="
											item1.disabled &&
												item1.disabled(scope.row)
										"
										:style="item1.style"
										:type="item1.btnType"
										size="mini"
										style="min-width: 45px;"
										@click="
											handleClick(
												item1.event,
												scope.row,
												item.eventArg || {}
											)
										"
									>
										<template v-if="item1.slot">
											<slot
												:name="'col-' + item1.prop"
												:row="scope.row"
												:scope="scope"
											/>
										</template>
										<template v-else>
											{{ item1.label }}
										</template>
									</el-button>
								</template>
							</template>
							<template v-else-if="item.filter && item.slot">
								<slot
									:name="'col-' + item.prop"
									:row="scope.row"
									:scope="scope"
								/>
							</template>
							<!-- solt自定义列-->
							<template v-else-if="item.slot">
								<slot
									:name="'col-' + item.prop"
									:row="scope.row"
									:scope="scope"
								/>
							</template>
							<!-- 带有数据过滤函数 -->
							<template v-else-if="item.filter">
								<Copy
									v-if="
										$t('common.components.test') &&
											item.showCopy
									"
									:copy="copy"
									:title="$t('common.components.test')"
								>
									{{ $t('common.components.test') }}
								</Copy>
								<!-- <Copy
                v-if="!!scope.row[item.prop]"
                :title="scope.row[item.prop]"
                :copy="copy"
              >
                {{ scope.row.userName }}
              </Copy> -->
								<span
									v-else
									:style="
										item.styleCellColor &&
											item.styleCellColor(
												scope.row[item.prop]
											)
									"
									@click="
										handleClick(
											item.event,
											scope.row,
											item.eventArg || {}
										)
									"
								>
									{{ item.filter(scope.row[item.prop]) }}
								</span>
							</template>
							<template v-else-if="item.func">
								<span>
									{{ item.func(scope.$index) }}
								</span>
							</template>
							<!-- 正常渲染数据- -->
							<template v-else>
								<span>
									{{ scope.row[item.prop] }}
								</span>
							</template>
						</template>
					</AFTableColumn>
				</template>
			</el-table>
		</el-table-draggable>
		<el-pagination
			v-show="pageObj.show"
			:current-page.sync="pageNum"
			:page-size="pageSize"
			:page-sizes="[10, 20, 50]"
			:total="pageObj.pageTotal"
			background
			class="main-table-pagination"
			layout="total, sizes,prev, pager, next, jumper"
			@current-change="handleCurrentChange"
			@size-change="handleSizeChange"
		/>
	</div>
</template>

<script>
import AFTableColumn from './AFTableColumn/index'
import { Decimal } from 'decimal.js'
import ElTableDraggable from 'el-table-draggable'

export default {
	name: 'CommonTable',
	components: {
		AFTableColumn,
		ElTableDraggable,
		Copy: () => import('@/components/Copy/copy')
	},
	props: {
		// 采用表头背景样式，默认为1 2为无背景
		headerStyle: {
			type: Number,
			default: 1
		},
		// 分页
		pageObj: {
			type: Object,
			default: () => {
				return {
					show: true,
					pageTotal: 0
				}
			}
		},
		// 序号
		xvhao: { type: Boolean, default: false },
		// 是否开启索引
		openIndex: { type: Boolean, default: false },
		loading: { type: Boolean, default: false },
		// 自定义类名
		className: {
			type: String,
			default: ''
		},
		// 表格字段配置
		fieldList: {
			type: Array,
			default: () => []
		},
		// 总数据
		datas: {
			type: Array,
			default: () => []
		},
		// 底部数据总计
		summary: {
			type: Object,
			default: () => {
				return {
					show: false,
					showTotal: false,
					datas: {},
					columns: [],
					cloneColumns: []
				}
			}
		},
		getSummariesObj: {
			type: Object,
			default: () => {}
		},
		// 字段排序后調用方法
		loadData: {
			type: Function,
			default: () => {}
		},
		pageKey: {
			type: String,
			default: ''
		},
		useColumnDrag: {
			type: Boolean,
			default: false
		},
		handler: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			pageSize: 100,
			// pageTotal: 0,
			pageNum: 1,
			pageSizes: [10, 20, 50, 100, 200],
			layout: 'total, sizes, prev, pager, next, jumper',
			times: Date.now(),
			ownSummary: {},
			defaultSort: {}
		}
	},
	computed: {
		username() {
			return window.localStorage.getItem('username')
		},
		curFieldList() {
			let pageKeyData = window.localStorage.getItem(
				`${this.username}-${this.pageKey}`
			)
			if (pageKeyData) {
				pageKeyData =
					typeof pageKeyData === 'string'
						? JSON.parse(pageKeyData)
						: pageKeyData
				return this.fieldList
					.map((item) => {
						return {
							...item,
							order: pageKeyData[item.prop]?.order
						}
					})
					.sort((a, b) => a.order - b.order)
			} else {
				return this.fieldList
			}
		}
	},
	watch: {
		'pageObj.pageTotal': {
			handler(newVal, oldVal) {
				if (!newVal) {
					return (this.pageNum = 1)
				}
				this.pageNum =
					(oldVal - 1) % this.pageSize === 0 && this.pageNum > 1
						? this.pageNum - 1
						: this.pageNum
				// this.loadData()
			},
			deep: true
		},
		summary: {
			handler(val) {
				this.$nextTick(() => {
					this.ownSummary = val
					this.times = Date.now()
				})
			},
			// immediate: true,
			deep: true
		}
	},

	methods: {
		handleDragSort(val) {
			// console.log('val', val)
		},
		handleDragInput(val) {
			this.$emit('handleDrag', val)
		},
		getParams(params) {
			// 重置的时候
			if (params && (params?.pageNum || params?.pageSize)) {
				this.pageNum = params.pageNum || this.pageNum
				this.pageSize = params.pageSize || this.pageSize
			}
			// 不重置 需要分页的时候
			return Object.assign(
				{
					pageNum: this.pageNum,
					pageSize: this.pageSize
				},
				params
			)
		},
		handleSizeChange(value) {
			this.pageNum = 1
			this.pageSize = value
			this.loadData()
		},
		handleCurrentChange(value) {
			this.pageNum = value
			this.loadData()
		},
		styleCellColor(style, val) {
			return val && style
		},
		copy(e) {
			if (e) {
				this.$copyText(e).then(() => {
					this.$message({
						type: 'success',
						message: this.$t('common.copy')
					})
				})
			}
		},
		changeTableSort({ column, prop, order }) {
			if (order) {
				order === 'ascending' ? (order = 'asc') : (order = 'desc')
				this.loadData({ orderType: order, orderKey: prop })
			} else {
				this.loadData({ orderType: undefined, orderKey: undefined })
			}
		},
		getRowClass({ row, column, rowIndex, columnIndex }) {
			if (rowIndex === 0 && this.headerStyle !== 2) {
				return 'background:#EFEFEF'
			} else {
				return ''
			}
		},
		handleClick(event, tableRow, args) {
			// console.warn(event, tableRow, args)
			if (event) {
				this.$emit(event, Object.assign({}, tableRow, args), args)
			}
		},
		filterSummar: function(val) {
			if (typeof val === 'number') {
				return (
					new Decimal(val).toFixed(3, Decimal.ROUND_DOWN) - 0
				).toLocaleString('en-us', {
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				})
			} else {
				return ''
			}
		},
		getColumnsLabel(property) {
			let label = ''
			this.ownSummary.columns?.map((prop) => {
				if (prop[property] !== undefined) {
					label = prop && prop[property] && prop[property]
				}
			})
			return label
		},
		// 小计 值
		getColumnsFitter(property, label, num) {
			let columnVal = ''
			this.ownSummary.columns?.map((item) => {
				if (item[property] !== undefined && label === item[property]) {
					// console.log(item[property], label, num, '--小计')
					if (item.filter) {
						columnVal = item.filter(num)
					} else {
						columnVal = num
					}
				}
			})
			return columnVal
		},

		// 总计 值
		getTotalColumnsFitter(property, label, num) {
			let columnVal = ''
			this.ownSummary.totalColumns?.map((item) => {
				if (item[property] !== undefined && label === item[property]) {
					if (item.filter) {
						columnVal = item.filter(this.ownSummary.datas[item.key])
					} else {
						columnVal = this.ownSummary.datas[item.key]
					}
				}
			})
			return columnVal
		},
		filterColor(totalColumns, property, label) {
			let colorVal = ''
			totalColumns?.map((item) => {
				if (item[property] !== undefined && label === item[property]) {
					if (item.style) {
						colorVal = item.style()
					}
				}
			})
			return colorVal
		},
		getSummaries(param) {
			const { columns, data } = param
			const sums = []
			// console.log(columns, data, this.ownSummary, '----')
			columns.forEach((column, index) => {
				if (index === 0) {
					const el = this.ownSummary.showTotal ? (
						<div class='count_row'>
							<p>{this.$t('common.components.sub_total')}</p>
							<p>{this.$t('common.components.total')}</p>
						</div>
					) : (
						<div class='count_row1'>
							<p>{this.$t('common.components.sub_total')}</p>
						</div>
					)
					sums[index] = el
					return
				} else if (
					column.label === this.getColumnsLabel(column.property) &&
					this.ownSummary.datas !== null
				) {
					const values = data.map((item) =>
						Number(item[column.property])
					)
					if (!values.every((value) => isNaN(value))) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr)
							if (!isNaN(value)) {
								return prev + curr
							} else {
								return prev
							}
						}, 0)
					}
					const num = sums[index] || 0
					sums[index] = this.ownSummary.showTotal ? (
						<div class='count_row'>
							<p
								style={this.filterColor(
									this.ownSummary.columns,
									column.property,
									column.label
								)}
							>
								{this.getColumnsFitter(
									column.property,
									column.label,
									num
								)}
							</p>
							<p
								style={this.filterColor(
									this.ownSummary.totalColumns,
									column.property,
									column.label
								)}
							>
								{this.getTotalColumnsFitter(
									column.property,
									column.label
								)}
							</p>
						</div>
					) : (
						<div class='count_row1'>
							<p
								style={this.filterColor(
									this.ownSummary.columns,
									column.property,
									column.label
								)}
							>
								{this.getColumnsFitter(
									column.property,
									column.label,
									num
								)}
							</p>
						</div>
					)
					return
				} else {
					this.ownSummary.showTotal ? (
						(sums[index] = (
							<div class='count_row'>
								<p />
								<p />
							</div>
						))
					) : (
						<div class='count_row1'>
							<p />
						</div>
					)
				}
			})

			return sums
		},
		setHeadClass({ row, rowIndex }) {
			return 'set-head-class'
		},
		getSerialNum(index) {
			return (this.pageNum - 1) * this.pageSize + index + 1
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
	padding: 0 !important;
}

.count_row {
	height: 80px;
	color: #5c5c5c;

	& > p:nth-child(1) {
		border-bottom: 1px solid #ebeef5;
	}

	p {
		height: 40px;
		line-height: 40px;
		font-weight: 700;

		span {
			display: inline-block;
			width: 20px;
			height: 20px;
		}
	}

	.enableColor {
		color: #13ce66;
	}

	.redColor {
		color: red;
	}
}

.count_row1 {
	height: 40px;
	color: #5c5c5c;

	p {
		height: 40px;
		line-height: 40px;
		font-weight: 700;

		span {
			display: inline-block;
			width: 20px;
			height: 20px;
		}
	}

	.enableColor {
		color: #13ce66;
	}

	.redColor {
		color: red;
	}
}

::v-deep .el-icon-s-operation::after {
	content: '\E7BB';
}

::v-deep .el-icon-s-operation::before {
	content: '';
}

::v-deep .el-table th,
.el-table tr {
	padding: 0 !important;
}

::v-deep .el-table__fixed,
.el-table__fixed-right {
	z-index: 999;
}

::v-deep .el-table thead {
	height: 47px;
	color: #5c5c5c;
}

// 表头列单元格
::v-deep .el-table th.el-table__cell > .cell {
	width: 110%;
}

::v-deep .el-table th > .cell {
	padding-left: 0;
	padding-right: 0;
}

.operation-icon {
	font-size: 15px;
	font-weight: 999;
	cursor: pointer;
}

.el-loading-spinner i {
	color: #409eff;
	font-size: 48px;
}

.el-table ::v-deep .DisabledSelection .cell .el-checkbox__inner {
	display: none;
	position: relative;
}

.el-table ::v-deep .DisabledSelection .cell:before {
	content: '#';
	position: absolute;
	right: 30px;
}

.el-table__header tr,
.el-table__header th {
	padding: 0;
	height: 30px;
}

.el-table__body tr,
.el-table__body td {
	padding: 0;
	height: 30px;
}

.el-table .cell,
.el-table--border td:first-child .cell,
.el-table--border th:first-child .cell {
	padding-left: 5px;
	font-size: 14px;
}

.el-table__fixed {
	background: #fff;
}

.el-table ::v-deep .el-table .sort-caret {
	width: 0;
	height: 0;
	border: 5px solid transparent;
	position: absolute;
	left: 5px;
}

.main-table-pagination {
	padding: 15px;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(255, 255, 255, 1);
	z-index: 99;
}
</style>
